package cn.iocoder.yudao.module.cms.appversion.service;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cms.appversion.dal.dataobject.AppVersionDO;
import cn.iocoder.yudao.module.cms.appversion.dal.mysql.AppVersionMapper;
import cn.iocoder.yudao.module.cms.appversion.vo.AppVersionPageReqVO;
import cn.iocoder.yudao.module.cms.appversion.vo.AppVersionSaveReqVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.cms.ErrorCodeConstants.APP_VERSION_NOT_EXISTS;

/**
 * 版本更新 Service 实现类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Service
@Validated
public class AppVersionServiceImpl implements AppVersionService {

    @Resource
    private AppVersionMapper appVersionMapper;

    @Override
    public Long createAppVersion(AppVersionSaveReqVO createReqVO) {
        // 插入
        AppVersionDO appVersion = BeanUtils.toBean(createReqVO, AppVersionDO.class);
        appVersionMapper.insert(appVersion);
        // 返回
        return appVersion.getId();
    }

    @Override
    public void updateAppVersion(AppVersionSaveReqVO updateReqVO) {
        // 校验存在
        validateAppVersionExists(updateReqVO.getId());
        // 更新
        AppVersionDO appVersionDO = BeanUtils.toBean(updateReqVO, AppVersionDO.class);
        appVersionMapper.updateById(appVersionDO);
    }

    @Override
    public void deleteAppVersion(Long id) {
        // 校验存在
        AppVersionDO appVersionDO = validateAppVersionExists(id);
        // 删除
        appVersionMapper.deleteById(appVersionDO);
    }

    private AppVersionDO validateAppVersionExists(Long id) {
        AppVersionDO appVersionDO = appVersionMapper.selectById(id);
        if (appVersionDO == null) {
            throw exception(APP_VERSION_NOT_EXISTS);
        }
        return appVersionDO;
    }

    @Override
    public AppVersionDO getAppVersion(Long id) {
        return appVersionMapper.selectById(id);
    }

    @Override
    public PageResult<AppVersionDO> getAppVersionPage(AppVersionPageReqVO pageReqVO) {
        return appVersionMapper.selectPage(pageReqVO);
    }

    @Override
    public AppVersionDO getLatestAppVersion(Integer type) {
        return appVersionMapper.selectLatestAppVersion(type);
    }

}
